﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using PIBV;
using System.Diagnostics;
using System.Data;

namespace MTViewer
{
    /// <summary>
    /// Interaction logic for ctrlActions.xaml
    /// </summary>
    public partial class ctrlActions : UserControl
    {
        PID_BlindingList _objBL = null;
        public event EventHandler<LoadDrawingEventArgs> OnDropDrawing;

        //temporary objects
        System.Drawing.Graphics _g;
        System.Drawing.Image _i_bmp;

        System.Drawing.Color _markerColor;
        int _markerWidth = 1;

        public ctrlActions()
        {
            InitializeComponent();
            _markerColor = Properties.Settings.Default.SelectionMarkerColor;
            _markerWidth = Properties.Settings.Default.SelectionMarkerWidth;
        }

        private void btnClearDrawings_Click(object sender, RoutedEventArgs e)
        {
            TouchObjectFactory.RemoveTouchObjectsFromCanvas();
        }

        private void btnFindPdfText_Click(object sender, RoutedEventArgs e)
        {
            UserControl ctrl = TouchObjectFactory.GetDbPanel();
            ITouchObject p = TouchObjectFactory.GetTopTouchObjectFromCanvas();
            
            if(TouchObjectFactory.IsDrawing(p))
            {
                System.Drawing.Image i_tiff = System.Drawing.Image.FromFile(p.ImagePath);

                _i_bmp = new System.Drawing.Bitmap(i_tiff.Width, i_tiff.Height);

                _g = System.Drawing.Graphics.FromImage(_i_bmp);
                _g.DrawImage(i_tiff, 0, 0, i_tiff.Width, i_tiff.Height);

                //Find text
                // Finding in DGN format is more prioritized - If dgn file exists - find in pdf converted from dgn
                //if (!String.IsNullOrWhiteSpace(p.DgnFileName))
                //{
                //    PIBV.AcrobatWrapper.FindText(txtFilter1.Text, Properties.Settings.Default.Pdf2StoragePath, p.DgnFileName.ChangeExtensionToPDF(), DrawQuads);
                //}
                //else
                //{
                    PIBV.AcrobatWrapper.FindText(txtFilter1.Text, Properties.Settings.Default.PdfStoragePath, p.PdfFileName, DrawQuads);
                //}

                string fName = Properties.Settings.Default.TempStoragePath + Guid.NewGuid().ToString() + ".tif";
                _i_bmp.Save(fName, System.Drawing.Imaging.ImageFormat.Tiff);
                p.ImagePath = fName;

                //dispose elements
                _g.Dispose();
                i_tiff.Dispose();
                _i_bmp.Dispose();
            }
        }
        
        void DrawQuads(PIBV.PDFQuadArgs a)
        {
            int bmpWidth = _i_bmp.Width;
            System.Drawing.PointF[] points = new System.Drawing.PointF[4] { NewCoord(a.p1, a.size, bmpWidth), NewCoord(a.p2, a.size, bmpWidth), NewCoord(a.p4, a.size, bmpWidth), NewCoord(a.p3, a.size, bmpWidth) };
            System.Drawing.Brush brush = new System.Drawing.SolidBrush(_markerColor);
            System.Drawing.Pen pen = new System.Drawing.Pen(brush,_markerWidth);
            _g.DrawPolygon(pen, points);
        }

        System.Drawing.PointF NewCoord(Point p, Point pdfSize, double imgWidth)
        {
            double k = (double)imgWidth / (double)pdfSize.X;
            System.Drawing.PointF r = new System.Drawing.PointF((float)(p.X * k), (float)((pdfSize.Y -p.Y) * k));
            return r;
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            ITouchObject p = TouchObjectFactory.GetTopTouchObjectFromCanvas();
            if (TouchObjectFactory.IsDrawing(p))
            {
                p.ImagePath = p.OriginalImagePath;
            }
        }

        private void btnCapMatrix_Click(object sender, RoutedEventArgs e)
        {
            if (OnDropDrawing != null)
            {
                LoadDrawingEventArgs args = new LoadDrawingEventArgs(new Point(400, 75), "capmatrix.cap", "", "", "", "");
                OnDropDrawing(this,args);
            }
        }

        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(Properties.Settings.Default.AppDownloaderName);
        }

        private void btnBlinding_Click(object sender, RoutedEventArgs e)
        {
            UserControl ctrl = TouchObjectFactory.GetDbPanel();
            ITouchObject p = TouchObjectFactory.GetTopTouchObjectFromCanvas();

            if (TouchObjectFactory.IsDrawing(p))
            {
                System.Drawing.Image i_tiff = System.Drawing.Image.FromFile(p.ImagePath);

                _i_bmp = new System.Drawing.Bitmap(i_tiff.Width, i_tiff.Height);

                _g = System.Drawing.Graphics.FromImage(_i_bmp);
                _g.DrawImage(i_tiff, 0, 0, i_tiff.Width, i_tiff.Height);
                
                //Draw VALVES
                if (_objBL == null)
                {
                    _objBL = App.DbManager.CreateObject<PID_BlindingList>();
                }
                
                int bmpWidth = _i_bmp.Width;
                int radius = 75;

                string pid = _objBL.GetPIDFromPDF(p.PdfFileName);

                DataTable tbl = _objBL.GetBlindingTagsForPID(pid);

                foreach(DataRow r in tbl.Rows)
                {
                    string pos = r["B_POSITION"].ToString();
                    string size = r["B_SIZE"].ToString();
                    string tag_type = r["B_TAG_TYPE"].ToString().ToUpper();

                    if(!String.IsNullOrWhiteSpace(pos))
                    {
                        string[] pos_coords = pos.Split(',');
                        string[] size_coords = size.Split(',');

                        System.Drawing.PointF point = NewCoord(new Point(Convert.ToInt32(pos_coords[0]), Convert.ToInt32(pos_coords[1])), new Point(Convert.ToInt32(size_coords[0]), Convert.ToInt32(size_coords[1])), bmpWidth);

                        System.Drawing.Color clr = System.Drawing.Color.Red;
 
                        switch (tag_type)
                        {
                            case "V": clr = System.Drawing.Color.Red;break;
                            case "B": clr = System.Drawing.Color.Green;break;
                            case "I": clr = System.Drawing.Color.Blue; break;
                        }

                        System.Drawing.Brush brush = new System.Drawing.SolidBrush(clr);
                        System.Drawing.Pen pen = new System.Drawing.Pen(brush, _markerWidth+5);
                        _g.DrawEllipse(pen, point.X - radius/2, point.Y - radius/2, radius, radius);
                    }
                }

                string fName = Properties.Settings.Default.TempStoragePath + Guid.NewGuid().ToString() + ".tif";
                _i_bmp.Save(fName, System.Drawing.Imaging.ImageFormat.Tiff);
                p.ImagePath = fName;

                //dispose elements
                _g.Dispose();
                i_tiff.Dispose();
                _i_bmp.Dispose();
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (OnDropDrawing != null)
            {
                LoadDrawingEventArgs args = new LoadDrawingEventArgs(new Point(400, 75), "blindinglist.bll", "", "", "", "");
                OnDropDrawing(this,args);
            }
        }

    }
}
